package com.zw.cloud.mybatis.plus.task.stenter;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.zw.cloud.mybatis.plus.entity.stenter.*;
import com.zw.cloud.mybatis.plus.service.api.stenter.IProductRecordDetailService;
import com.zw.cloud.mybatis.plus.service.api.stenter.IProductRecordService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;

/**
 * 排产未生产滞留超时提醒
 */
@Component
@Slf4j
public class ProductRetentionTask {

    @Autowired
    private IProductRecordService productRecordService;
    @Autowired
    private IProductRecordDetailService productRecordDetailService;


    public List<ProductRetentionDTO> updateProductRetention() {
        List<String> orgCodeList = Lists.newArrayList("devController");
        LocalDateTime now = LocalDateTime.now();
        List<ProductRetentionDTO> retentionDTOList = new CopyOnWriteArrayList<>();
        orgCodeList.parallelStream().forEach(orgCode -> {
            ProductRetentionDTO productRetentionDTO = checkOverTime(orgCode, now);
            if (Objects.nonNull(productRetentionDTO)) {
                retentionDTOList.add(productRetentionDTO);
                // WS
            }
        });
        return retentionDTOList;
    }

    private ProductRetentionDTO checkOverTime(String orgCode,LocalDateTime now) {
        // 查询配置

        try {
            String config = config();
            List<RetentionConfigDTO> receiverDTOList = JSON.parseArray(config, RetentionConfigDTO.class);
            if (CollectionUtils.isEmpty(receiverDTOList)) {
                return null;
            }
            long count = receiverDTOList.stream().map(receiverDTO -> Objects.nonNull(receiverDTO.getValue())).count();
            if (count < 1) {
                return null;
            }

            Set<Integer> receiveLevelSet = new HashSet<>();
            Map<Integer, RetentionConfigDTO> receiverDTOMap = receiverDTOList.stream().collect(Collectors.toMap(RetentionConfigDTO::getLevel, v -> v, (k1, k2) -> k2));


            List<ProductRecord> productRecordList = productRecordService.queryNotStartProductRecord(orgCode);
            if (CollectionUtils.isEmpty(productRecordList)) {
                return null;
            }

            List<ProductRecordDetail> needUpdateList = new ArrayList<>();
            Long maxTime = null;
            for (ProductRecord productRecord : productRecordList) {
                List<Long> overTimeList = Lists.newArrayList();
                Long overTime1 = checkOverTimeByLevel(productRecord, now, receiverDTOMap.get(1),overTimeList,receiveLevelSet);
                Long overTime2 = checkOverTimeByLevel(productRecord, now, receiverDTOMap.get(2),overTimeList,receiveLevelSet);
                Long overTime3 = checkOverTimeByLevel(productRecord, now, receiverDTOMap.get(3),overTimeList,receiveLevelSet);
                if (Objects.isNull(overTime1) && Objects.isNull(overTime2) && Objects.isNull(overTime3)) {
                    continue;
                }
                Long max = overTimeList.stream().max(Comparator.comparing(s -> s)).get();
                if (Objects.isNull(maxTime) || max > maxTime) {
                    maxTime = max;
                }
                ProductRecordDetail productRecordDetail = new ProductRecordDetail();
                productRecordDetail.setProductRecordId(productRecord.getId());
                productRecordDetail.setRetention(1);
                needUpdateList.add(productRecordDetail);
            }
            if (CollectionUtils.isEmpty(needUpdateList)) {
                return null;
            }
            ProductRetentionDTO productRetentionDTO = new ProductRetentionDTO();
            productRetentionDTO.setOrgCode(orgCode);
            productRetentionDTO.setOverMaxTime(maxTime);
            productRetentionDTO.setRecordCount(needUpdateList.size());
            Set<String> receiveUserSet = new HashSet<>();
            receiveLevelSet.forEach(level -> {
                List<OperatorInfoDTO> receiverList = receiverDTOMap.get(level).getReceiverList();
                if (CollectionUtils.isEmpty(receiverList)) {
                    return;
                }
                receiveUserSet.addAll(receiverList.stream().map(OperatorInfoDTO::getUserId).collect(Collectors.toSet()));
            });
            productRetentionDTO.setReceiveUserSet(receiveUserSet);
            productRecordDetailService.insertOrUpdateBatch(needUpdateList);
            return productRetentionDTO;
        } catch (Exception e) {
            log.error("[ProductRetentionTask][updateProductRetention]orgCode is {}, error is ",orgCode,e);
        }
        return null;
    }

    private Long checkOverTimeByLevel(ProductRecord productRecord,LocalDateTime now,RetentionConfigDTO retentionConfigDTO,List<Long> overTimeList,Set<Integer> receiveLevelSet) {
        if (Objects.isNull(retentionConfigDTO)) {
            return null;
        }
        Integer value = retentionConfigDTO.getValue();
        if (Objects.isNull(value)) {
            return null;
        }
        Duration between = Duration.between(productRecord.getCreateTime(), now);
        // TODO 上线时修改为 小时
        //long hours = between.toHours();
        long hours = between.toMinutes();
        if (hours >= value) {
            overTimeList.add(hours);
            receiveLevelSet.add(retentionConfigDTO.getLevel());
            return hours;
        }
        return null;
    }

    private String config() {
        return "[\n" +
                "    {\n" +
                "        \"name\":\"一级滞留时常\",\n" +
                "        \"level\":1,\n" +
                "        \"value\":5,\n" +
                "        \"receiverList\":[\n" +
                "            {\n" +
                "                \"userId\":\"1F554F5D9B9A407CAB596438FB925BD6\",\n" +
                "                \"userName\":\"刘雪萍\"\n" +
                "            }\n" +
                "        ]\n" +
                "    },\n" +
                "    {\n" +
                "        \"name\":\"二级滞留时常\",\n" +
                "        \"level\":2,\n" +
                "        \"value\":10,\n" +
                "        \"receiverList\":[\n" +
                "            {\n" +
                "                \"userId\":\"417797CD22564E9F9D948FFD3D5ED56B\",\n" +
                "                \"userName\":\"郑宇鹏\"\n" +
                "            }\n" +
                "        ]\n" +
                "    },\n" +
                "    {\n" +
                "        \"name\":\"三级滞留时常\",\n" +
                "        \"level\":3,\n" +
                "        \"value\":20,\n" +
                "        \"receiverList\":[\n" +
                "            {\n" +
                "                \"userId\":\"274E55A16FDA452B93D645D1409B2DAF\",\n" +
                "                \"userName\":\"朱会龙\"\n" +
                "            }\n" +
                "        ]\n" +
                "    }\n" +
                "]";
    }
}
